import 'package:dio/dio.dart';
import 'dart:io';
import 'api_client.dart';
import 'app_config.dart';

class ApiService {
  static final ApiService _instance = ApiService._internal();
  factory ApiService() => _instance;
  ApiService._internal();

  final ApiClient _client = ApiClient();

  // 认证相关API
  Future<Response> login(String username, String password) async {
    return await _client.post(
      '/auth/login',
      data: {
        'tenantId': AppConfig.tenantId,
        'username': username,
        'password': password,
        'rememberMe': true,
        'clientId': AppConfig.clientId,
        'grantType': 'password',
      },
    );
  }

  Future<Response> register(
    String username,
    String password,
    String email,
  ) async {
    return await _client.post(
      '/auth/register',
      data: {'username': username, 'password': password, 'email': email},
    );
  }

  Future<Response> refreshToken(String refreshToken) async {
    return await _client.post(
      '/auth/refresh',
      data: {'refresh_token': refreshToken},
    );
  }

  // 用户画像相关API
  Future<Response> saveUserProfile(Map<String, dynamic> profile) async {
    return await _client.post('/profile/save', data: profile);
  }

  // 保存用户额外信息
  Future<Response> saveUserExtraInfo(Map<String, dynamic> extraInfo) async {
    // 验证必要参数
    final requiredFields = ['grade', 'volume', 'subjects', 'goals'];
    for (final field in requiredFields) {
      if (!extraInfo.containsKey(field) ||
          extraInfo[field] == null ||
          extraInfo[field].toString().isEmpty) {
        throw Exception('用户必须完成所有选择，缺少参数: $field');
      }
    }

    return await _client.post('/system/user/saveExtraInfo', data: extraInfo);
  }

  // 获取用户额外信息
  Future<Response> getUserExtraInfo() async {
    return await _client.get('/system/user/getExtraInfo');
  }

  Future<Response> getUserProfile() async {
    return await _client.get('/profile');
  }

  Future<Response> updateUserProfile(Map<String, dynamic> profile) async {
    return await _client.put('/profile', data: profile);
  }

  // OCR识别相关API
  Future<Response> ocrRecognize(File imageFile) async {
    final formData = FormData.fromMap({
      'image': await MultipartFile.fromFile(
        imageFile.path,
        filename: imageFile.path.split('/').last,
      ),
    });

    return await _client.upload('/ocr/recognize', formData: formData);
  }

  // AI聊天会话相关API
  Future<Response> createChatSession() async {
    return await _client.post('/dromara/coze/create/session');
  }

  // AI聊天：发送消息
  Future<Response> sendChatMessage({
    required String conversationId,
    required String message,
    String userId = 'system_user_001',
  }) async {
    return await _client.post(
      '/dromara/coze/send/message/$conversationId',
      data: {
        'conversationId': conversationId,
        'message': message,
        'userId': userId,
      },
    );
  }

  // AI聊天：查询回答状态（轮询）
  Future<Response> getChatStatus({
    required String conversationId,
    required String chatId,
  }) async {
    return await _client.get(
      '/dromara/coze/status/chat/$conversationId/$chatId',
    );
  }

  // AI聊天：根据 chatId 获取该次AI回复内容
  Future<Response> getChatMessages({
    required String conversationId,
    required String chatId,
  }) async {
    return await _client.get(
      '/dromara/coze/chat-messages/$conversationId/$chatId',
    );
  }

  // 兜底：按会话获取最近消息列表（用于发送成功但缺少chatId时，尝试获取最新一条）
  Future<Response> getConversationMessages({
    required String conversationId,
  }) async {
    return await _client.get('/dromara/coze/history/messages/$conversationId');
  }

  // AI聊天：上传文件（multipart/form-data, field: file）
  Future<Response> uploadFile(File file) async {
    final formData = FormData.fromMap({
      'file': await MultipartFile.fromFile(
        file.path,
        filename: file.path.split('/').last,
      ),
    });
    return await _client.upload(
      '/dromara/coze/upload/file',
      formData: formData,
    );
  }

  // AI讲解相关API
  Future<Response> getExplanation({
    required String question,
    String? imageUrl,
    String? stage,
    String? subject,
  }) async {
    return await _client.post(
      '/ai/explain',
      data: {
        'question': question,
        'image_url': imageUrl,
        'stage': stage,
        'subject': subject,
      },
    );
  }

  Future<Response> getSimilarQuestions(String questionId) async {
    return await _client.get('/ai/similar/$questionId');
  }

  // 学习计划相关API
  Future<Response> generateStudyPlan(Map<String, dynamic> params) async {
    return await _client.post('/plan/generate', data: params);
  }

  Future<Response> getStudyPlan() async {
    return await _client.get('/plan');
  }

  Future<Response> updateStudyPlan(
    String planId,
    Map<String, dynamic> updates,
  ) async {
    return await _client.put('/plan/$planId', data: updates);
  }

  // 错题本相关API
  Future<Response> addMistake(Map<String, dynamic> mistake) async {
    return await _client.post('/mistakes', data: mistake);
  }

  Future<Response> getMistakes({
    String? subject,
    String? status,
    int? page,
    int? limit,
  }) async {
    return await _client.get(
      '/mistakes',
      queryParameters: {
        'subject': subject,
        'status': status,
        'page': page,
        'limit': limit,
      },
    );
  }

  Future<Response> updateMistake(
    String mistakeId,
    Map<String, dynamic> updates,
  ) async {
    return await _client.put('/mistakes/$mistakeId', data: updates);
  }

  Future<Response> deleteMistake(String mistakeId) async {
    return await _client.delete('/mistakes/$mistakeId');
  }

  // 学习统计相关API
  Future<Response> getLearningStats({String? period, String? subject}) async {
    return await _client.get(
      '/stats/learning',
      queryParameters: {'period': period, 'subject': subject},
    );
  }

  Future<Response> getProgressReport() async {
    return await _client.get('/stats/progress');
  }

  // 练习题库相关API
  Future<Response> getPracticeQuestions({
    String? subject,
    String? difficulty,
    String? knowledgePoint,
    int? count,
  }) async {
    return await _client.get(
      '/practice/questions',
      queryParameters: {
        'subject': subject,
        'difficulty': difficulty,
        'knowledge_point': knowledgePoint,
        'count': count,
      },
    );
  }

  Future<Response> submitAnswer(
    String questionId,
    Map<String, dynamic> answer,
  ) async {
    return await _client.post('/practice/answer/$questionId', data: answer);
  }

  // 文件上传相关API
  Future<Response> uploadFileV2(File file, {String? type}) async {
    final formData = FormData.fromMap({
      'file': await MultipartFile.fromFile(
        file.path,
        filename: file.path.split('/').last,
      ),
      if (type != null) 'type': type,
    });

    return await _client.upload('/upload', formData: formData);
  }

  // 系统配置相关API
  Future<Response> getAppConfig() async {
    return await _client.get('/config/app');
  }

  Future<Response> getSubjects() async {
    return await _client.get('/config/subjects');
  }

  Future<Response> getStages() async {
    return await _client.get('/config/stages');
  }
}
